package com.ice.work.moment.socket.controller;

import com.honeybee.cloud.framework.common.idwork.IdWorker;
import com.honeybee.cloud.framework.common.response.ResponseEntity;
import com.ice.work.moment.facade.socket.controller.ISocketController;
import com.ice.work.moment.facade.socket.params.ImgMessageParam;
import com.ice.work.moment.facade.socket.request.PushMessageRequest;
import com.ice.work.moment.facade.socket.store.GlobalStore;
import com.ice.work.moment.socket.call.CheckTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.concurrent.BasicFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Description socket
 * @Author DELL
 * @Create 2019-05-24
 * @Since 1.0.0
 */
@RestController
@Slf4j
public class SocketController implements ISocketController {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ExecutorService executorService;

    @Override
    public ResponseEntity<String> pushMessage(PushMessageRequest request) {
        ImgMessageParam messageParam = new ImgMessageParam();
        messageParam.setMessage(request.getMessage());
        Long taskId = idWorker.nextId();
        messageParam.setId(taskId);
        GlobalStore.WEB_SOCKET_CLIENT.forEach((key, client) -> {
            try {
                client.sendEvent("sendMessage", messageParam);
            } catch (Exception e) {
                log.error("推送消息异常", e);
            }
        });
        CheckTask checkThread = new CheckTask();
        executorService.execute(new Thread(checkThread));
        BasicFuture<String> basicFuture = new BasicFuture(null);
        GlobalStore.CHECK_REQUEST.put(taskId, basicFuture);
        String check = null;
        try {
            check = basicFuture.get(6000, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("识别验证码异常", e);
        }
        return ResponseEntity.ok(check);
    }
}
